import { CallHandler, Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common'
import { getClientIp } from 'request-ip'
import { Observable } from 'rxjs'
import moment from 'moment'
import { ConfigService } from '@donews/nestjs-config'
import { CoreException, CoreExceptionType } from '@/modules'

@Injectable()
export class RequestInterceptor implements NestInterceptor {
    constructor(private readonly config: ConfigService) {}
    public async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
        const request = context.switchToHttp().getRequest()
        const version = this.config.get('client')
        if (
            request.headers?.version &&
            !request.url.includes('queryVersion') &&
            !request.originalUrl.includes('queryVersion') &&
            request.headers.version !== version.version
        ) {
            throw new CoreException(CoreExceptionType.ERROR_VERSION_IS_OLD)
        }
        request.time = moment().format('YYYY-MM-DD HH:mm:ss')
        const ip = getClientIp(request)
        request.body = { ...(request?.body || {}), __user: request?.user, __ip: ip, __token: request.authorization }
        return next.handle()
    }
}
